package initialize

import (
	"context"
	"fmt"
	"github.com/vueadmin/global"
	"go.mongodb.org/mongo-driver/event"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"os"
	"time"
)

// 链接mongodb
func GetMongoClient(dsn string, database string) *mongo.Database {
	clientOptions := options.Client().ApplyURI(dsn).SetConnectTimeout(5 * time.Second).SetMonitor(&event.CommandMonitor{
		Started: func(ctx context.Context, evt *event.CommandStartedEvent) {
			global.LOG.Debug("mongodb执行语句:", evt.Command.String())
		},
	})
	clientOptions.SetMaxPoolSize(50)
	client, err := mongo.Connect(context.TODO(), clientOptions)

	if err != nil {
		fmt.Println("mongodb链接失败：", err)
		os.Exit(1)
	}
	err = client.Ping(context.Background(), nil) //ping通才代表连接成功
	if err != nil {
		fmt.Println("mongodb链接失败：", err)
		os.Exit(1)
	}
	return client.Database(database)
}
